package com.xinsoft.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xinsoft.entity.dto.SysUserCommonFunDTO;
import com.xinsoft.entity.po.SysUserCommonFun;
import com.xinsoft.service.SysMenuService;
import com.xinsoft.service.SysUserCommonFunService;
import com.xinsoft.mapper.SysUserCommonFunMapper;
import com.xinsoft.utils.TokenUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
* @author hsm
* @description 针对表【sys_user_common_fun(用户常用功能)】的数据库操作Service实现
* @createDate 2023-11-20 15:17:08
*/
@Service
public class SysUserCommonFunServiceImpl extends ServiceImpl<SysUserCommonFunMapper, SysUserCommonFun>
    implements SysUserCommonFunService{

    @Resource
    private SysMenuService sysMenuService;

    @Override
    public List<SysUserCommonFunDTO> findList() {
        QueryWrapper query = new QueryWrapper<SysUserCommonFun>().eq("user_id", TokenUtil.getUserId()).orderByAsc("sort");
        List<SysUserCommonFun> list = list(query);
        List<SysUserCommonFunDTO> result = new ArrayList<>();

        for (SysUserCommonFun sysUserCommonFun : list) {
            SysUserCommonFunDTO record = new SysUserCommonFunDTO();
            BeanUtils.copyProperties(sysUserCommonFun,record);
            record.setSysMenu(sysMenuService.getById(sysUserCommonFun.getMenuId()));
            result.add(record);
        }
        return result;
    }

    @Override
    public void editSysUserCommonFun(List<SysUserCommonFun> sysUserCommonFunList) {
        //先删除原有设置
        QueryWrapper removeQuery = new QueryWrapper<SysUserCommonFun>().eq("user_id", TokenUtil.getUserId());
        remove(removeQuery);
        if(CollectionUtil.isNotEmpty(sysUserCommonFunList)){
            for (SysUserCommonFun sysUserCommonFun : sysUserCommonFunList) {
                sysUserCommonFun.setUserId(TokenUtil.getUserId());
            }
        }
        saveBatch(sysUserCommonFunList);
        //再保存最新的设置
    }
}